package com.gjs.cd.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjs.cd.manager.MakeCode;
import com.gjs.cd.mapper.CdCodeGenerateBatchMapper;
import com.gjs.cd.mapper.CodeMapper;
import com.gjs.cd.pojo.dto.TotalReq;
import com.gjs.cd.pojo.entity.CdCodeActivationRecord;
import com.gjs.cd.pojo.entity.CdCodeGenerateBatch;
import com.gjs.cd.pojo.entity.CdCodeValidTerm;
import com.gjs.cd.pojo.entity.Code;
import com.gjs.cd.pojo.vo.CodeVo;
import com.gjs.cd.service.ICdCodeActivationRecord;
import com.gjs.cd.service.ICdCodeGenerateBatchService;
import com.gjs.cd.service.ICdCodeValidTermService;
import com.gjs.cd.service.ICodeService;
import com.gjs.common.enums.entity.QuarterEnum;
import com.gjs.common.exception.BizException;
import com.gjs.common.pojo.dto.request.PageQuery;
import com.gjs.common.pojo.dto.response.ListPageRsp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * @author zhongwenguang
 * @date 2022-3-9 18:04
 */

@Service
@Slf4j
@EnableAsync
public class CodeServiceImpl extends ServiceImpl<CodeMapper, Code> implements ICodeService {

    @Autowired
    private CodeMapper codeMapper;

    @Autowired
    private ICdCodeGenerateBatchService iCdCodeGenerateBatchService;

    @Autowired
    private ICdCodeValidTermService iCdCodeValidTermService;

    @Autowired
    private ICdCodeActivationRecord iCdCodeActivationRecord;

    @Override
    public int add(Long batchId,int num) {
        int targetNum = num;
        CdCodeGenerateBatch cdCodeGenerateBatch = iCdCodeGenerateBatchService.getById(batchId);
        String tableName = cdCodeGenerateBatch.getPreTableName();//获取表名
        Long validTermId = cdCodeGenerateBatch.getCdId();
        Integer quarter = iCdCodeValidTermService.getById(validTermId).getCodeQuarter().getCode();//获取季度
        int maxNum = 30000;//单词最大插入数量
        int total = 0;//统计插入数量,初始值为0
        try{
            while (num>0){
                MakeCode makeCode = new MakeCode();
                List<Code> list = new ArrayList<>();
                if (num>maxNum){
                    list = makeCode.createCode(tableName,batchId,quarter,maxNum);
                }else{
                    list = makeCode.createCode(tableName,batchId,quarter,num);
                }
                total+=codeMapper.insertCode(list,tableName);
                num -= maxNum;
            }
        }catch (Exception e){
            cdCodeGenerateBatch.setRealNum(total);
            cdCodeGenerateBatch.setStatus(2);
            iCdCodeGenerateBatchService.updateById(cdCodeGenerateBatch);
            throw new BizException("新增激活码失败！");
        }
        cdCodeGenerateBatch.setRealNum(total);
        if (total == targetNum){
            cdCodeGenerateBatch.setStatus(1);
        }else {
            cdCodeGenerateBatch.setStatus(2);
        }
        iCdCodeGenerateBatchService.updateById(cdCodeGenerateBatch);
        return total;
    }

    @Override
    public IPage<CodeVo> queryBatch(PageQuery pageQuery, Long batchId) {
        LambdaQueryWrapper<Code> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(batchId != 0,Code::getBatchId,batchId);
        lambdaQueryWrapper.orderByDesc(Code::getId);
        IPage<Code> codeIPage = this.page(pageQuery.buildPage(),lambdaQueryWrapper);
        //获取codeId
        List<Long> codeIds = new ArrayList<>();
        for (int i=0;i<codeIPage.getRecords().size();i++){
            codeIds.add(codeIPage.getRecords().get(i).getId());
        }
        //统计激活码的激活次数
        String tableName = iCdCodeGenerateBatchService.getById(batchId).getPreTableName();
        List<TotalReq> totalReqList = iCdCodeActivationRecord.getTotalByIds(tableName,codeIds);
        Map<Long,Long> map = totalReqList.size()>0 ? totalReqList.stream().collect(toMap(TotalReq::getId,TotalReq::getTotal)):null;

        IPage<CodeVo> codeVoIPage = codeIPage.convert(u->{
            CodeVo v = new CodeVo();
            BeanUtil.copyProperties(u,v);
            v.setActivationNum(map.get(u.getId()));
            return v;
        });
        return codeVoIPage;
    }

    @Override
    public Code queryByCode(String tableName, String code) {
        return codeMapper.queryByCode(tableName,code);
    }

    @Override
    public List<String> queryTable() {
        return codeMapper.queryTable();
    }

    @Override
    public List<Code> queryByTableNames(List<String> tableNameList, List<Long> ids) {
        return codeMapper.queryByTableNames(tableNameList,ids);
    }

    @Override
    public List<Code> queryCodeList(String tableName, List<Long> ids) {
        return codeMapper.queryCodeList(tableName,ids);
    }
}
